<template>
  <div class="admin-dashboard">
    <!-- 数据概览卡片 -->
    <div class="stats-grid">
      <el-card class="stats-card" shadow="hover" v-loading="loading">
        <div class="stats-content">
          <div class="stats-icon users">
            <el-icon :size="36"><User /></el-icon>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ formatNumber(statsCard.totalUsers) }}</div>
            <div class="stats-label">总用户数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stats-card" shadow="hover" v-loading="loading">
        <div class="stats-content">
          <div class="stats-icon stations">
            <el-icon :size="36"><Shop /></el-icon>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ formatNumber(statsCard.totalStations) }}</div>
            <div class="stats-label">回收站点</div>
          </div>
        </div>
      </el-card>

      <el-card class="stats-card" shadow="hover" v-loading="loading">
        <div class="stats-content">
          <div class="stats-icon orders">
            <el-icon :size="36"><Document /></el-icon>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ formatNumber(statsCard.totalOrders) }}</div>
            <div class="stats-label">总订单数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stats-card" shadow="hover" v-loading="loading">
        <div class="stats-content">
          <div class="stats-icon revenue">
            <el-icon :size="36"><Money /></el-icon>
          </div>
          <div class="stats-info">
            <div class="stats-value">¥{{ formatMoney(statsCard.totalRevenue) }}</div>
            <div class="stats-label">总收入</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 最新订单和站点状态 -->
    <div class="content-section">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="24" :md="12" :lg="12">
          <el-card shadow="hover" class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">最新订单</span>
                <el-button type="primary" size="small" link>
                  查看全部
                </el-button>
              </div>
            </template>
            <el-table :data="recentOrders" v-loading="loading" style="width: 100%">
              <el-table-column prop="orderNo" label="订单号" min-width="150" show-overflow-tooltip />
              <el-table-column prop="customerName" label="客户" width="100" />
              <el-table-column label="金额" width="100">
                <template #default="scope">
                  <span class="amount-text">¥{{ formatMoney(scope.row.totalAmount) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)" size="small">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="!loading && recentOrders.length === 0" class="empty-state">
              <el-empty description="暂无订单数据" :image-size="80" />
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="24" :md="12" :lg="12">
          <el-card shadow="hover" class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">站点状态</span>
                <el-button type="primary" size="small" link @click="$router.push('/admin/stations')">
                  管理站点
                </el-button>
              </div>
            </template>
            <div class="station-list" v-loading="loading">
              <div 
                v-for="station in stationStatus" 
                :key="station.id" 
                class="station-item"
              >
                <div class="station-info">
                  <div class="station-name">{{ station.name }}</div>
                  <div class="station-load">
                    负载: {{ station.currentLoad }}/{{ station.capacity }} kg
                  </div>
                </div>
                <div class="station-status">
                  <el-tag 
                    :type="getStationStatusType(station.status)" 
                    size="small"
                  >
                    {{ getStationStatusText(station.status) }}
                  </el-tag>
                  <el-progress 
                    :percentage="Math.round((station.currentLoad / station.capacity) * 100)" 
                    :stroke-width="8"
                    :show-text="false"
                    :color="getProgressColor(station.currentLoad / station.capacity)"
                    class="load-progress"
                  />
                </div>
              </div>
            </div>
            <div v-if="!loading && stationStatus.length === 0" class="empty-state">
              <el-empty description="暂无站点数据" :image-size="80" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <el-card shadow="hover">
        <template #header>
          <span class="card-title">快捷操作</span>
        </template>
        <div class="action-buttons">
          <el-button 
            type="primary" 
            :icon="UserFilled" 
            size="large"
            @click="$router.push('/admin/users')"
          >
            用户管理
          </el-button>
          <el-button 
            type="success" 
            :icon="Box" 
            size="large"
            @click="$router.push('/admin/items')"
          >
            物品管理
          </el-button>
          <el-button 
            type="info" 
            :icon="Shop" 
            size="large"
            @click="$router.push('/admin/stations')"
          >
            站点管理
          </el-button>
          <el-button 
            type="warning" 
            :icon="DataAnalysis" 
            size="large"
            @click="$router.push('/admin/analysis')"
          >
            数据分析
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { dashboardAPI } from '@/api'
import {
  User,
  Shop,
  Document,
  Money,
  UserFilled,
  Box,
  DataAnalysis
} from '@element-plus/icons-vue'

// 组件名称
defineOptions({
  name: 'AdminDashboard'
})

// 响应式数据
const loading = ref(false)

// 统计数据
const statsCard = ref({
  totalUsers: 0,
  totalStations: 0,
  totalOrders: 0,
  totalRevenue: 0
})

// 最新订单
const recentOrders = ref([])

// 站点状态
const stationStatus = ref([])

// 获取仪表板数据
const fetchDashboardData = async () => {
  loading.value = true
  try {
    const data = await dashboardAPI.getDashboardStats()
    
    if (data) {
      statsCard.value = data.statsCard || statsCard.value
      recentOrders.value = data.recentOrders || []
      stationStatus.value = data.stationStatus || []
    }
  } catch (error) {
    console.error('获取仪表板数据失败:', error)
    ElMessage.error('获取数据失败，请刷新重试')
  } finally {
    loading.value = false
  }
}

// 格式化数字
const formatNumber = (num) => {
  if (!num && num !== 0) return '0'
  return num.toLocaleString('zh-CN')
}

// 格式化金额
const formatMoney = (amount) => {
  if (!amount && amount !== 0) return '0.00'
  const num = typeof amount === 'string' ? parseFloat(amount) : amount
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 状态映射函数
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: '',
    in_progress: 'info',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || '未知'
}

const getStationStatusType = (status) => {
  const types = {
    active: 'success',
    busy: 'warning',
    closed: 'danger'
  }
  return types[status] || 'info'
}

const getStationStatusText = (status) => {
  const texts = {
    active: '正常',
    busy: '繁忙',
    closed: '关闭'
  }
  return texts[status] || '未知'
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage < 0.6) return '#67C23A'
  if (percentage < 0.8) return '#E6A23C'
  return '#F56C6C'
}

onMounted(() => {
  fetchDashboardData()
})
</script>

<style scoped>
.admin-dashboard {
  padding: 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stats-card {
  border-radius: 12px;
  transition: transform 0.2s;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 8px 0;
}

.stats-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.stats-icon.users {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.stations {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.orders {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.revenue {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
  min-width: 0;
}

.stats-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1.2;
  margin-bottom: 6px;
  font-family: 'Arial', 'Helvetica', sans-serif;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  font-weight: 400;
}

.content-section {
  margin-bottom: 24px;
}

.table-card {
  border-radius: 12px;
  min-height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.amount-text {
  color: #67C23A;
  font-weight: 600;
  font-family: 'Arial', sans-serif;
}

/* 左侧表格字体调整 */
.table-card :deep(.el-table) {
  font-size: 15px;
}

.table-card :deep(.el-table th) {
  font-size: 15px;
}

.table-card :deep(.el-table td) {
  font-size: 15px;
}

.station-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 300px;
}

.station-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  transition: all 0.2s;
}

.station-item:hover {
  background: #ecf5ff;
}

.station-info {
  flex: 1;
  min-width: 0;
}

.station-name {
  font-weight: 600;
  font-size: 15px;
  color: #303133;
  margin-bottom: 6px;
}

.station-load {
  font-size: 13px;
  color: #606266;
}

.station-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.load-progress {
  width: 100px;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.quick-actions {
  margin-bottom: 24px;
}

.quick-actions .el-card {
  border-radius: 12px;
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 16px;
}

.action-buttons .el-button {
  height: 48px;
  font-size: 15px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-value {
    font-size: 24px;
  }
  
  .action-buttons {
    grid-template-columns: 1fr;
  }
  
  .load-progress {
    width: 80px;
  }
}
</style>
